<script lang="ts" setup>
import { AuthenticationLogin } from '@vben/common-ui';

import { useAuthStore } from '#/store';
import { reactive, ref, onMounted, h} from 'vue';
import { uctoo_wechatopen } from '#/store';
import { useRepo } from 'pinia-orm';
import { useAxiosRepo } from '@pinia-orm/axios';
import { useRoute } from 'vue-router';
import { message , Modal} from 'ant-design-vue';
import { $t } from '@vben/locales';
// 获取当前路由信息
const route = useRoute();
// 获取查询字符串部分
let queryParam = reactive({ ...route.query });
defineOptions({ name: 'WechatAuthorization' });

const authStore = useAuthStore();
const showVerifyCode = ref(true);
onMounted(async () => {
  console.log(queryParam);
  


  const isWeChat = () => {
    const ua = navigator.userAgent.toLowerCase()
      return ua.includes('micromessenger')
    }

  if (isWeChat()) {
    //  uni.showToast({  title: '当前在微信环境中',  icon: 'none',   duration: 2000   })

    try {
      /*
      const logparam = {
        appid: config.appid,
        code: options.code,
        state: options.state
      }
  
      const serverLog = await getServerlog(logparam) */
      // 1. 首先检查 URL 中是否有 code 参数
      if (queryParam?.code) {
        // 如果有 code，说明是微信回调，直接处理授权
        const paramTokenData = {
          appid: import.meta.env.VITE_WEBSITE_APPID,
          code: queryParam?.code,
          state: queryParam?.state,
          client_id:queryParam?.client_id
        }
        const oauthToken = await useAxiosRepo(uctoo_wechatopen).api().postOauthCallback(paramTokenData)
        if (oauthToken && oauthToken.response.data.access_token) {
        //  setClientToken(oauthToken.access_token)
        } else {
       //   uni.showToast({ title: 'token登录失败，请稍后再试', icon: 'none' })
       message.error('token登录失败，请稍后再试');
        }
        if (oauthToken && oauthToken.response.data.user) {
        //  uni.setStorageSync('userInfo', oauthToken.user)
        //
          Modal.success({
            title: `${$t('page.loginSuccess')}`,
            content: h('div', {}, [
              h('p', `${$t('authentication.welcomeBack')}`)
            ]),
            onOk() {
              window.close();
            },
          });
        }
      } else {
        // 没有token也无code
        // 2. 如果没有 code，说明是首次访问，需要进行微信授权
        const paramOauthData = {
          appid: import.meta.env.VITE_WEBSITE_APPID,
          redirect_scene: 'wechatAuthorization',
          client_id:queryParam?.client_id
        }
        const oauthUrl = await useAxiosRepo(uctoo_wechatopen).api().getOauthRedirect(paramOauthData);
  
        console.log('res', oauthUrl);
        if (oauthUrl && oauthUrl.response.data.oauthUrl) {
          window.location.href = oauthUrl.response.data.oauthUrl
        } else {
        //  uni.showToast({ title: 'oauth授权失败，请稍后再试', icon: 'none' })
        message.error('oauth授权失败，请稍后再试');
        }
      }
      //微信授权登录成功后的业务逻辑

      
    } catch (error) {
      console.error('登录过程出错：', error)
      message.error('登录过程出错：');
     // uni.showToast({ title: 'error登录失败，请稍后再试', icon: 'none' })
    }
  } else {
    console.error('isWeChat：', isWeChat())
    //  uni.showToast({ title: '当前不在微信环境中', icon: 'none', duration: 2000 })
    // 微信外场景只能用 H5支付通道
  }
});
</script>

<template>
  
</template>
